package graph.editor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.JOptionPane;

import observable.ObservableAutomaton;
import automaton.NotDeterministiTransitionException;
import automaton.NotDeterministicInitialStateException;
import automaton.TransitionImpl;
import automaton.UnknownInitialStateException;

public class RunFrame {

	List<Vertex> vertices = new ArrayList<Vertex>();
	List<Edge> edges = new ArrayList<Edge>();
	GraphComponent component;
	HashMap<Vertex, NewState> hm = new HashMap<>();

	public RunFrame(GraphComponent component) {
		// TODO Auto-generated constructor stub
		this.component=component;
		this.vertices = component.vertices;
		this.edges = component.edges;
		// inital hashmap
		for (Vertex v : this.vertices) {
			// hm.put(v, new StateImpl(false, false, v.label));
			hm.put(v, new NewState(false, false, v.label, v));
		}
		
	}

	public ObservableAutomaton<String> run()
			throws NotDeterministiTransitionException,
			NotDeterministicInitialStateException, UnknownInitialStateException {
		// TODO Auto-generated method stub

		ArrayList<TransitionImpl> transitions = new ArrayList<>();

		for (Edge e : edges) {
			// transitions.add(new NewTransition<String>(hm.get(e.v1), hm
			// .get(e.v2), e.textField.getText()));
			transitions.add(new TransitionImpl<String>(hm.get(e.v1), hm
					.get(e.v2), e.textField.getText()));
		}
		try {
			transitions.get(0).source().setState(true, false);
		} catch (Exception e) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(null, "Please draw the figure");
		}

		// transitions.get(transitions.size() -
		// 1).target.setState(false,
		// true);
//		 transitions.get(0).source().setState(true, false);
	
		// transitions.get(transitions.size() -
		// 1).target().setState(false,
		// true);
		for (TransitionImpl<String> tran : transitions) {

			if (((NewState) tran.source()).nVertex.getFinstate() == true) {
				tran.source().setState(false, true);

			}
			if (((NewState) tran.target()).nVertex.getFinstate() == true) {
				tran.target().setState(false, true);

			}
			
			((NewState) tran.source()).nVertex.setColor(component.getForeground());
		}
		if (((NewState) transitions.get(0).source()).nVertex.getFinstate() == true
				& ((NewState) transitions.get(0).source()).nVertex
						.getInistate() == true) {
			transitions.get(0).source().setState(true, true);
		//	((NewState) transitions.get(0).source()).nVertex.setFinstate(false);

		}
		TransitionImpl<String>[] trans = new TransitionImpl[transitions.size()];
		ObservableAutomaton<String> ob = new ObservableAutomaton<String>(
				transitions.toArray(trans));

		return ob;

	}

}
